package com.gf.common.util;

import java.util.Enumeration;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gf.base.type.LicenseState;
import com.gf.base.type.Role;
import com.gf.common.constant.Constants;
import com.gf.common.exception.BusinessException;
import com.gf.common.exception.NotLoginException;
import com.gf.common.exception.NotOperationEexception;
import com.gf.user.model.Ticket;
import com.gf.user.model.User;

public class WebHelper {
	// ticket的有效时间
	private static long TICKET_VALID_TIME = 24 * 60 * 60 * 1000;

	/**
	 * 根据传入的request情况获取实际的request，如果不为空则不做任何改变 如果传入request为空则获取当前线程中设置的request
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * 
	 * */
	public static HttpServletRequest initRequest(HttpServletRequest request) {
		if (request == null) {
			request = RequestContainer.getRequest();
		}
		if (request == null) {
			throw new BusinessException(
					"business exception");
		}
		return request;
	}

	/**
	 * 根据传入的response情况获取实际的response，如果不为空则不做任何改变
	 * 如果传入response为空则获取当前线程中设置的response
	 * 
	 * @param response
	 *            传入的HttpServletResponse 可以为空
	 * 
	 * */
	public static HttpServletResponse initResponse(HttpServletResponse response) {
		if (response == null) {
			response = ResponseContainer.getResponse();
		}

		if (response == null) {
			throw new BusinessException(
					"business exception");
		}
		return response;
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	@SuppressWarnings("unchecked")
	public static <T> T getSessionAttribute(HttpServletRequest request,
			String key) {
		request = initRequest(request);
		return (T) request.getSession().getAttribute(key);
	}

	/**
	 * 
	 * @param key
	 * @return
	 */
	public static <T> T getSessionAttribute(String key) {
		return getSessionAttribute(null, key);
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	public static void setSessionAttribute(HttpServletRequest request,
			String key, Object value) {
		request = initRequest(request);
		request.getSession().setAttribute(key, value);
		// 用户session存在的最长时间为2h 以 秒 为单位
		if (key.equals(Constants.SESSION_ACTIVE_USER_TICKET)) {
			request.getSession().setMaxInactiveInterval(3600 * 2);
		} else if (key.equals(Constants.SESSION_USER)) {
			request.getSession().setMaxInactiveInterval(3600 * 3);
		}
	}

	/**
	 * 
	 * @param key
	 * @param value
	 */
	public static void setSessionAttribute(String key, Object value) {
		setSessionAttribute(null, key, value);
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	public static String getSessionId(HttpServletRequest request) {
		request = initRequest(request);
		return request.getSession().getId();
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	public static void removeSessionAttribute(HttpServletRequest request,
			String key) {
		request = initRequest(request);
		request.getSession().removeAttribute(key);
	}

	/**
	 * 
	 * @param key
	 */
	public static void removeSessionAttribute(String key) {
		removeSessionAttribute(null, key);
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	public static void invalidateSession(HttpServletRequest request) {
		request = initRequest(request);
		request.getSession().invalidate();
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	@SuppressWarnings("rawtypes")
	public static Enumeration getSessionAttributeNames(
			HttpServletRequest request) {
		request = initRequest(request);
		return request.getSession().getAttributeNames();
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	public static long getSessionCreationTime(HttpServletRequest request) {
		request = initRequest(request);
		return request.getSession().getCreationTime();
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	public static long getSessionLastAccessedTime(HttpServletRequest request) {
		request = initRequest(request);
		return request.getSession().getLastAccessedTime();
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	public static boolean isSessionNew(HttpServletRequest request) {
		request = initRequest(request);
		return request.getSession().isNew();
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	public static void setSessionMaxInactiveInterval(
			HttpServletRequest request, int value) {
		request = initRequest(request);
		request.getSession().setMaxInactiveInterval(value);
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	public static int getSessionMaxInactiveInterval(HttpServletRequest request) {
		request = initRequest(request);
		return request.getSession().getMaxInactiveInterval();
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	public static void saveToken(HttpServletRequest request) {
		request = initRequest(request);
		String token = UUID.randomUUID().toString();
		request.getSession()
				.setAttribute(Constants.SESSION_SUBMIT_TOKEN, token);
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	@Deprecated
	public static boolean isTokenValid(HttpServletRequest request, boolean reset) {
		request = initRequest(request);
		String token = request.getParameter("submitToken");
		return isTokenValid(request, reset, token);
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	public static boolean isTokenValid(HttpServletRequest request,
			boolean reset, String token) {
		request = initRequest(request);
		String sessionToken = (String) request.getSession().getAttribute(
				Constants.SESSION_SUBMIT_TOKEN);
		boolean result = false;
		if (token == null || !token.equals(sessionToken)) {
			result = false;
		} else {
			result = true;
		}
		if (reset) {
			saveToken(request);
		}
		return result;
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * */
	public static String getClientIp(HttpServletRequest request) {
		request = initRequest(request);
		String ipAddress = request.getRemoteAddr();
		ipAddress = request.getHeader("X-Forwarded-For");
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
		}

		// 对于通过多个代理的情况，第一个IP非unknown为客户端真实IP,多个IP按照','分割
		while (ipAddress != null && ipAddress.indexOf(",") > 0) {
			String addr = ipAddress.substring(0, ipAddress.indexOf(","));
			if (addr == null || addr.length() == 0
					|| "unknown".equalsIgnoreCase(addr)) {
				ipAddress = ipAddress.substring(ipAddress.indexOf(",") + 1);
			} else {
				ipAddress = addr;
				break;
			}

		}
		return ipAddress;
	}

	/**
	 * 查看SESSION中ticket是否有效:时间为 TICKET_VALID_TIME
	 * 
	 * @param request
	 *            可以为空
	 * @param key
	 *            : SESSION_ACTIVE_USER_TICKET,SESSION_FIND_PASSWD_TICKET
	 * @return
	 */
	public static boolean isTicketSessionValid(HttpServletRequest request,
			String key) {
		request = initRequest(request);
		Ticket ticket = getSessionAttribute(request, key);

		long now = System.currentTimeMillis();
		if ((now - ticket.getCreatetime().getTime()) <= TICKET_VALID_TIME) {
			return true;
		} else {
			return false;
		}

	}

	/**
	 * 取得你当前运行文件在服务器上的绝对路径<br>
	 * 例：D:\codes\workspace\workspace-grid\.metadata\.plugins\org.eclipse.wst.
	 * server.core\tmp0\wtpwebapps\Baibai\
	 * 
	 * @return
	 */
	public static String getRealPath() {
		return initRequest(null).getSession().getServletContext()
				.getRealPath("/");
	}

	/**
	 * 取得当前session里用户的角色
	 * 
	 * @return 超级管理员 true
	 */
	public static boolean checkAdminControl() {
		User user = getSessionAttribute(null, Constants.SESSION_USER);
		if (user == null) {
			throw new NotOperationEexception("need admin access");
		} else if (Role.ADMIN.toString().equals(user.getRole().toString())) {
			return true;
		}

		return false;
	}

	/**
	 * 取得当前session里用户的角色
	 * 
	 * @return 超级管理员 true
	 */
	public static boolean checkSuperControl() {
		User user = getSessionAttribute(null, Constants.SESSION_USER);
		if (user == null) {
			throw new NotOperationEexception("need super access");
		} else if (Role.SUPER.toString().equals(user.getRole().toString())) {
			return true;
		}

		return false;
	}

	/**
	 * 从session里得到当前用户<br>
	 * 无抛出异常
	 * 
	 * @return
	 */
	public static User getSessionUser() {
		User user = getSessionAttribute(Constants.SESSION_USER);
		if (user == null) {
			throw new NotLoginException();
		} else {
			return user;
		}
	}

	/**
	 * 检查是否有发布项目的权利<br>
	 * 并得到当前user
	 * 
	 * @return
	 */
	public static User checkAuthorityOfPublish() {
		User user = getSessionUser();
		if (user.getRole() == Role.NORMAL) {
			throw new NotOperationEexception(" you have not right to publish");
		}
		else{
			if(user.getLicenseState()!=LicenseState.PASSED){
				throw new NotOperationEexception("you licenese is not passed or not upload!");
			}
		}

		return user;
	}
	
}
